#include <iostream>
#include <memory>
#include <vector>
#include <algorithm>
using namespace std ;


class Book
{
private:
    
public:
    Book(const string &bookTitle) :title(bookTitle){}
    ~Book(){cout<< "Destroying Book:"<<title<<endl;}
    string title;
};
typedef shared_ptr<Book> BookPtr;

static void DeleteBook(Book* ptrBook)
{
    cout<< "Custom deleter for a Book"<<ptrBook->title<<endl;
    delete ptrBook;
}

static bool Comparetitles (BookPtr ptr1,BookPtr ptr2)
{
    return (ptr1->title < ptr2->title);
}

static void PrintBookTitles (const vector<BookPtr>& books)
{
    for (int i =0 ;i <books.size();++i)
    {
        cout << books[i]->title<<endl;
    }
}


static void shared_ptr_demo()
{
    BookPtr bookptr (new Book("C++"));
    string title = bookptr->title;
    int use_count=bookptr.use_count();
    cout <<"Reference count for book "<<bookptr->title<<"is" << bookptr.use_count()<<endl;

    BookPtr bookptr2(bookptr);
    title=bookptr->title;
    use_count=bookptr.use_count();
    cout <<"Reference count for book "<<bookptr->title<<"is" << bookptr.use_count()<<endl;

    bookptr->title="java";
    cout <<"change one ptr "<<bookptr->title<<"," << bookptr2->title<<endl;

    vector<BookPtr> books ;
    books.push_back(BookPtr(new Book("c")));
    books.push_back(BookPtr(new Book("python")));
    books.push_back(BookPtr(new Book("c#")));

    cout << "before sorting"<<endl;
    PrintBookTitles(books);
    sort(books.begin(),books.end(),Comparetitles);

    cout << "after sorting"<<endl;
    PrintBookTitles(books);


    // 自定义析构函数
    BookPtr bookptr3 (new Book("small c++"),DeleteBook);
    bookptr3.reset();
    


}
int main(int, char**) {
    std::cout << "Hello, world!\n";
    shared_ptr_demo();
    return  0;
}
